package com.example.farmeri.ui.news;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.farmeri.R;
import com.example.farmeri.adapter.NoticeAdapter;
import com.example.farmeri.common.BaseRecycleOnScrollListener;
import com.example.farmeri.data.DataParam;
import com.example.farmeri.pojo.Messages;
import com.example.farmeri.presenter.message.IMessageContract;
import com.example.farmeri.presenter.message.MessagePresenter;
import com.example.farmeri.ui.base.BaseFragment;
import com.example.farmeri.adapter.MyItemDecoration;
import com.example.farmeri.ui.login.model.LoginData;
import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class NewsFragment extends BaseFragment<MessagePresenter> implements IMessageContract{

    @BindView(R.id.fragment_notice_recycle_view)
    RecyclerView recyclerView;
    @BindView(R.id.fragment_notice_more)
    View more;
    @BindView(R.id.fragment_notice_chart)
    BarLineChartBase chart;

    private Map<Integer,String > data; //访问的日期
    private Map<Integer,Integer > times; //访问的次数

    private static NewsFragment fragment;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = getLayoutInflater().inflate(R.layout.fragment_notice,container,false);
        ButterKnife.bind(this,view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        init();

        fetchData();
        // 消息显示更多
        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), NewsManagerActivity.class));
            }
        });
    }

    private void init() {
        present = new MessagePresenter(this);
        initRecycleView();
        initToolBar(R.id.fragment_notice_toolbar,"通知消息",false,false);
        //initChart();


    }

    private void fetchData() {
        String id = DataParam.getUserInfo().getId();
        present.getLoginDate(id);
        present.getMessages(id,1,999);
    }

    private void initChart() {
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置X轴坐标之间的最小间隔
        xAxis.setGranularity(1f);
        //设置X轴的刻度数量
        xAxis.setLabelCount(12,false);
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(13f);
        //得到月份
        xAxis.setValueFormatter(new IndexAxisValueFormatter(){
            @Override
            public String getFormattedValue(float value) {
                return data.get((int)value);
            }
        });
        //得到Y轴
        YAxis rightYAxis = chart.getAxisRight();
        YAxis leftYAxis = chart.getAxisLeft();
        //隐藏
        rightYAxis.setEnabled(false);
        //限制Y轴高度
        leftYAxis.setAxisMinimum(0);
        //设置Y轴坐标之间的最小间隔
        leftYAxis.setGranularity(2f);
        List<BarEntry> loginCount = new ArrayList<>();
        for (int i=1;i<=times.size();i++) {
            loginCount.add(new BarEntry(i, times.get(i)));
        }
        BarDataSet barDataSet = new BarDataSet(loginCount, "访问量");
        barDataSet.setColor(ContextCompat.getColor(getContext(),R.color.colorRed));
        barDataSet.setValueFormatter(new IndexAxisValueFormatter(){
            @Override
            public String getFormattedValue(float value) {
                return String.valueOf((int)value);
            }
        });
        List<IBarDataSet> barDataSetList = new ArrayList<>();
        barDataSetList.add(barDataSet);
        // add entries to dataset
        BarData barData = new BarData(barDataSetList);

        //Description
        Description description = new Description();
        description.setEnabled(false);
        chart.setDescription(description);
        //设置当前图标最多显示多少个刻度
        chart.setVisibleXRangeMaximum(6);
        chart.setData(barData);
        chart.invalidate(); // refresh
    }

    private void initRecycleView() {
        SharedPreferences sp = getActivity().getSharedPreferences(getResources().getString(R.string.share_preference_user_info), Context.MODE_PRIVATE);
        String id = sp.getString(getResources().getString(R.string.user_info_key_id),"");
        present.getMessages(id,1,10);
    }

    public void onLoginDataResult(LoginData loginData){
        data = new HashMap<>();
        times = new HashMap<>();
        data.put(0,"");
        data.put(8,"");
        for (int i=0;i<loginData.getLoginDate().size();i++){
            data.put(i+1,loginData.getLoginDate().get(i));
            times.put(i+1,loginData.getLoginTimes().get(i));
        }
        initChart();
    }

    @Override
    public void onLoginDataError(String message) {
        if (null != message){
            showMessage(message);
        }
    }

    public void onMessageResult(Messages messages){
        NoticeAdapter adapter = new NoticeAdapter(getContext(),R.layout.item_notice,messages);
        recyclerViewAddData(recyclerView,adapter, LinearLayoutManager.VERTICAL,MyItemDecoration.MIDDLE_LINE);
        recyclerView.addOnScrollListener(new BaseRecycleOnScrollListener() {
            @Override
            public void onLoadMore() {
                adapter.setLoadState(adapter.LOADING_COMPLETE);
            }
        });
    }

    @Override
    public void onMessageError(String message) {
        if (null != message){
            showMessage(message);
        }

    }

    public void showMessage(String  message) {
        showToast(message);
    }

    public static NewsFragment newInstance() {
        if (fragment == null){
            return new NewsFragment();
        }
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        fragment = null;
        recyclerView = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        fragment = null;
        recyclerView = null;
    }
}
